package com.wsc.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.wsc.domain.Conversation;
import com.wsc.mapper.ConversationMapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Administrator
 */
@Component
public class MysqlChatMemory implements ChatMemory {
    @Autowired
    private ConversationMapper conversationMapper;

    @Override
    public void add(String conversationId, List<Message> messages) {
        //添加会话记录
        List<Conversation> list = messages.stream().map(message -> Conversation.builder()
                .conversationId(conversationId)
                .message(message.getText())
                .type(message.getMessageType().getValue())
                .createTime(LocalDateTime.now())
                .build()).toList();
        conversationMapper.insert(list);
    }

    @Override
    public List<Message> get(String conversationId) {

        List<Conversation> conversations = conversationMapper.selectList(
                new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId)
        );
        return conversations.stream().map(conversation ->
        {
            Message message = null;
            if (MessageType.USER.getValue().equals(conversation.getType())) {
                message = new UserMessage(conversation.getMessage());
            } else if (MessageType.ASSISTANT.getValue().equals(conversation.getType())) {
                message = new AssistantMessage(conversation.getMessage());
            }
            return message;
        }).toList();
    }

    @Override
    public void clear(String conversationId) {
        conversationMapper.delete(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId, conversationId));
    }
}
